package com.besttone.search;

import java.io.File;

import com.besttone.http.UpdateRequest;
import com.besttone.http.UpdateRequest.UpdateListener;
import com.besttone.search.dialog.ProgressBarDialog;
import com.besttone.search.model.City;
import com.besttone.search.model.PhoneInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.LogUtils;
import com.besttone.search.util.PhoneUtil;
import com.besttone.search.util.SharedUtils;
import com.besttone.search.util.StringUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class SplashActivity extends Activity {
	private final int TIME_UP = 1;
	protected Context mContext;
	protected UpdateRequest r;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == TIME_UP) {
				Intent intent = new Intent();
				intent.setClass(SplashActivity.this, MainActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.splash_screen_fade,
						R.anim.splash_screen_hold);
				SplashActivity.this.finish();
			}
		}
	};

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.splash_screen_view);
		initApp();
		initCity();
		initPhoneInfo();
		
		Client.initWithContext(this);

		detectUpdate();
//		new Thread() {
//			public void run() {
//				try {
//					Thread.sleep(500);
//				} catch (Exception e) {
//
//				}
//				Message msg = new Message();
//				msg.what = TIME_UP;
//				handler.sendMessage(msg);
//			}
//		}.start();

	}

	private void initApp() {
		initNativeDB();
	}

	private void initNativeDB() {
		SharedPreferences localSharedPreferences = getSharedPreferences(
				"NativeDB", 0);
		if (1 > localSharedPreferences.getInt("Version", 0)) {
			Constants.copyNativeDB(this,
					getResources().openRawResource(R.raw.native_database));
			localSharedPreferences.edit().putInt("Version", 1).commit();
		}
		Constants.copyNativeDB(this,
				getResources().openRawResource(R.raw.native_database));
		localSharedPreferences.edit().putInt("Version", 1).commit();
	}
	
	private boolean isUnSelectedCity() {
		if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentCityName(this.mContext)))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentCityCode(this.mContext)))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentProvinceCode(this.mContext)))) {
			return true;
		}
		return false;
	}
	
	private void initCity() {
		City localCity = new City();
		localCity.setCityName("上海");
		localCity.setCityCode("310000");
		localCity.setSimplifyCode("31");
		localCity.setCityId("75");
		localCity.setProvinceCode("310000");
		SharedUtils.setCurrentCity(this, localCity);
	}
	
	public void initPhoneInfo() {
		TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId(); //IMEI
		String provider = tm.getNetworkOperatorName(); //运营商
		String imsi = tm.getSubscriberId(); //IMSI
		PhoneUtil util = new PhoneUtil();
		PhoneInfo info = null;
		try {
			if(NetWorkStatus()) {
				//info = util.getPhoneNoByIMSI(imsi);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(info==null)
			info = new PhoneInfo();
		info.setImei(imei);
		info.setImsi(imsi);
		info.setProvider(provider);
		SharedUtils.setCurrentPhoneInfo(this, info);
	}
	
    private boolean NetWorkStatus() {
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
    	}
//    	if (netSataus) {
//    		Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?");
//    		b.setPositiveButton("是", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				Intent mIntent = new Intent("/");
//    				ComponentName comp = new ComponentName("com.android.settings", 
//    						"com.android.settings.WirelessSettings");
//    				mIntent.setComponent(comp);
//    				mIntent.setAction("android.intent.action.VIEW");
//    				startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写
//    			}
//    		}).setNeutralButton("否", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				dialog.cancel();
//    			}
//    		}).show();	
//    	}
    	return netSataus;
    }
    
    private void detectUpdate() {
    	r = new UpdateRequest();
		r.setListener(new UpdateListener() {
			@Override
			public void onUpdateNoNeed(String msg) {
				gotoLogin();
			}
			
			public void onUpdateMust(String msg, final String url) {
				AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
				b.setTitle("程序必须升级才能继续");
				b.setMessage(msg+"\r\n"+url);
				b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						System.gc();
					}
				});
				b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						gotoUpdate(url);
					}
				});
				b.setCancelable(false);
				b.show();
				
			}
			
			public void onUpdateError(short code, Exception e) {
				AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
				b.setTitle("升级验证失败");
				b.setMessage("请检查网络...");
				b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
						System.gc();
					}
				});
				b.setCancelable(false);
				b.show();
			}
			
			public void onUpdateAvaiable(String msg, final String url) {
				AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
				b.setTitle("程序可以升级，请选择");
				b.setMessage(msg+"\r\n"+url);
				b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						gotoLogin();
					}
				});
				b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						gotoUpdate(url);
					}
				});
				b.setCancelable(false);
				b.show();
			}
		});
		
		if (Client.decetNetworkOn())
		{
//			Log.d("check","on");
			r.checkUpdate();
		}
		else {
//			Log.d("check","off");
			gotoLogin();
			Toast.makeText(Client.getContext(), "网络异常，没有可用网络",
					Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void gotoLogin() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(500);
				} catch (Exception e) {

				}
				Message msg = new Message();
				msg.what = TIME_UP;
				handler.sendMessage(msg);
			}
		}.start();
	}
    private void gotoUpdate(String url) {

		if (TextUtils.isEmpty(url)) {
    		Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show();
    		finish();
    		System.gc();
    		return;
    	}
//		url = url.toLowerCase();
		if (url.startsWith("www")) {
			url = "http://" + url;
		}
		if (url.startsWith("http")) {
	    	try {
//	    		Uri u = Uri.parse(url);
	    		ProgressBarDialog pbd=new ProgressBarDialog(Client.getContext());
	    		pbd.setTitle("下载中");
	    		pbd.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						gotoLogin();
					}
				});
	    		pbd.show();
	    		pbd.downLoadFile(url);
//	    		Intent i = new Intent( Intent.ACTION_VIEW, u );
//	    		startActivity( i );
//	    		finish();
	    		System.gc();
	    	} catch(Exception e) {
	    		e.printStackTrace();
	    	}
		}
	}
}
